import openhtf as htf
from openhtf.output.servers import station_server
from openhtf.output.web_gui import web_launcher
from openhtf.plugs import user_input
from openhtf.util import configuration
from openhtf.plugs.user_input import UserInput
import logging
from openhtf.util import multicast
from openhtf.output.callbacks import mfg_inspector
from openhtf.output.proto import mfg_event_converter
import servers.my_station_server as my_station_server
from datetime import datetime
CONF = configuration.CONF


@htf.measures(htf.Measurement("hello_world_measurement"))
def hello_world(test):
    test.logger.info("Hello World!")
    test.attach("test_attachment","hello world.".encode("utf-8"))
    test.measurements.hello_world_measurement = "Hello Again!"


@htf.plug(user_input=UserInput)
def prompt_operator_next(test, user_input):
  is_connected = user_input.prompt(
      message="Click Okay when the LED turn on",
      text_input=False, # Button prompt from operator
  )

@htf.measures(
    htf.Measurement("led_color").with_validator(
        lambda color: color in ["Red", "Green", "Blue"]
    )
)
@htf.plug(user_input=UserInput)
def prompt_operator_led_color(test, user_input):
    led_color = user_input.prompt(
        message="What is the LED color? (Red/Green/Blue)",
        text_input=True,  # Text prompt from operator
    )
    test.measurements.led_color = led_color

@htf.plug(user_input=UserInput)
def prompt_dut_id(test, user_input):
    dut_id = user_input.prompt(
        message="Enter Your Dut SN",
        text_input=True,  # Text prompt from operator
    )
    test.test_record.dut_id = dut_id

def operator_start():
    @htf.plug(user_input=UserInput)
    def prompt_operator_start(test, user_input):
         user_input.prompt(
            f"""Please Enter Okay to Start Test""", text_input=False,)
        # test.test_record.dut_id = dut_id
    return prompt_operator_start

def main():
    interface = mfg_inspector.MfgInspector()
    interface.set_converter(mfg_event_converter.mfg_event_from_test_record)
    CONF.load(station_server_port="4444",station_discovery_ttl = 10)
    with my_station_server.MyStationServer(history_path="./history") as server:
        web_launcher.launch("http://localhost:4444")
        while True:
        # server.station_multicast.
            test = htf.Test(
                prompt_dut_id,
                hello_world,
                prompt_operator_next,
                prompt_operator_led_color,test_name="Openhtf-example")
            test.add_output_callbacks(
                server.publish_final_state,
                interface.save_to_disk(filename_pattern="./history/mfg_event_{dut_id}_{start_time_millis}.pb"))
            test.execute(test_start=operator_start())
            


if __name__ == "__main__":
    main()
